package com.xtaller.lazy.lib.kit;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.lazy.lib.convert.M;
import lombok.var;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * @version V1.0
 * @author: Taller
 * @date: 2019-04-03
 * @Description: 图片处理类
 */
public class ImgUtil {
    /**
     * 读取网络上的图片转成base64
     * */
    public static Map urlImg2Base64(String imgUrl){
        InputStream inputStream = null;
        var token = "";
        ByteArrayOutputStream outputStream = null;
        byte[] buffer = null;
        try {
            // 创建URL
            URL url = new URL(imgUrl);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            inputStream = conn.getInputStream();
            outputStream = new ByteArrayOutputStream();
            // 将内容读取内存中
            buffer = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            buffer = outputStream.toByteArray();

            Map<String, List<String>> map = conn.getHeaderFields();
            token = map.get("token").toString().replace("[", "").replace("]", "");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    // 关闭inputStream流
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    // 关闭outputStream流
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 对字节数组Base64编码
        return M.create("img", new BASE64Encoder().encode(buffer).replace("\n", "")).put("token", token);
    }
}
